import React,{ useState } from 'react';
import { View, Text, ScrollView,
  StyleSheet,
  Alert,
  FlatList,
  TouchableOpacity, 
  Modal,
  Dimensions,
  Image} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { List,ListItem,Button,Input,Divider,Card,Badge,Slider,Icon} from 'react-native-elements'
import { LinearProgress } from "@rneui/base";
import Carousel from 'react-native-looped-carousel';
import Ionicons from 'react-native-vector-icons/Ionicons';
import FontAwesome5Icon from 'react-native-vector-icons/FontAwesome5';
import moment from 'moment'
import Shop from './src/store/shop/shoppage'
import Personal from './src/personal/personal'
import Login from './src/personal/login'
import Records from './src/records'
// 'blue' '../../component/colors';
// import { YHFormatZero } from '../utilityClass/YHUtility';

const Tab = createBottomTabNavigator();
const HomeStack = createNativeStackNavigator();

export default function HomeStackScreen() {
  return (
    <NavigationContainer>
      <HomeStack.Navigator>
        <HomeStack.Screen name="Home" options={{headerShown:false}} component={App} />
        <HomeStack.Screen name="Focus" component={FocusScreen} />
        <HomeStack.Screen name="Login" component={Login} />
        <HomeStack.Screen name="Records" component={Records} />
      </HomeStack.Navigator>
    </NavigationContainer>
  );
}

function App() {
  // const [selectedId, setSelectedId] = useState(null);
  return (
      <Tab.Navigator
          screenOptions={({ route }) => ({
            tabBarIcon: ({ focused, color, size }) => {
              let iconName;
              if (route.name === 'Home') {
                iconName = focused
                  ? 'home'
                  : 'home-outline';
              } else if (route.name === 'Tree Store') {
                iconName = focused ? 'md-earth' : 'md-earth-outline';
              } else if (route.name === 'Personal') {
                iconName = focused ? 'md-body' : 'md-body-outline';
              }
              // You can return any component that you like here!
              return <Ionicons name={iconName} size={size} color={color} />;
            },
          tabBarActiveTintColor: 'tomato',
          tabBarInactiveTintColor: 'gray',
        })}
      >
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Tree Store" component={Shop} options={{
            // headerShown:false,
            headerStyle: {
              backgroundColor: '#f4511e',
            },
            headerShadowVisible:true,
            headerTintColor: '#fff',
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign:'center'
          }}/>
        <Tab.Screen name="Personal" component={Personal} />
      </Tab.Navigator>
  );
}

var TimingView = ({ duration,thing,tree,stop}) => {
  // console.log(Date.now())
  const [span, setSpan] = useState('');
  const [flag, setFlag] = useState(0);
  const [hour, setHour] = useState(0);
  const [h,setH] = useState(0);
  const [minute, setMinute] = useState(0);
  const [m,setM] = useState(0);
  const [second, setSecond] = useState(0);
  const [s,setS] = useState(0);
  React.useEffect(() => {
      const timing = setInterval(() => {
        if(!stop){
          setS(s+1);
          if(flag==0)
          {setSpan(moment().format('LTS'));setFlag(1);}
          if (s == 60) {
            setS(0);
            setM(m+1);
          }
          if (m == 60) {
            setM(0);
            setH(h+1);
          }
          var sec = s > 9 ? s : '0' + s;
          setSecond(sec)
          var min = m > 9 ? m : '0' + m;
          setMinute(min)
          setHour(h)
        } 
          setFlag(flag+1)
      }, 1000); // 计时结束时
      if((h*60+m) == duration){        // 数据记录下来
        clearInterval(timing);
        setSecond('00');
        var min = m > 9 ? m : '0' + m;
        setMinute(min);setHour(h);
        var record = {thing:thing,id:moment().format('LTS'),tree:tree,duration:duration,stage:3,finish:true,bt:span,et:moment().format('LTS')}
        // console.log(JSON.stringify(record));
        fetch(`http://192.168.1.106:3000/records`, {
            method:'POST',
            headers: {
              'Content-type': 'application/json'
            },
            body: JSON.stringify(record)
        })
        Alert.alert("It's time ⏰",'Congratulations on focusing on the expected time !\nThe tree planting information have been saved');return;
      }
      return () => clearInterval(timing);
  });

  return (
      <View style={{alignItems: 'center',top:17}}>
        <Card containerStyle={{width:298,backgroundColor:'lightblue',borderRadius:6}} wrapperStyle={{}}>
          <Text style={[styles.title,{textAlign: 'center',fontSize:27}]}>Time:{hour}:{minute}:{second}/{duration}</Text>
          <Card.Divider  width={1.5} style={{margin:8}} color="#41ae3c"/>
          <Text style={[styles.title,{textAlign: 'center'}]}>{moment().format('MMMM Do YYYY, h:mm:ss a')}</Text>
        </Card>
      </View>
  );
};

function FocusScreen({ route, navigation }){
  const {thing,time,tree} = route.params
  var stages = [{id:1,url: require('./images/树苗3.png')},{id:1,url: require('./images/树苗1.png')},{id:1,url: require('./images/树苗2.png')}]
  var trees= [{id:1,url: require('./images/首页1.png')},{id:2,url: require('./images/首页2.png')},{id:3,url: require('./images/首页3.png')},
  {id:4,url: require('./images/首页4.png')},{id:5,url: require('./images/首页5.png')},{id:6,url: require('./images/首页6.png')}]
  stages.push(trees[tree-1])
  const [progress, setProgress] = React.useState(0)
  const [stage,setStage] = React.useState(0)
  const [grow,setGrow] = React.useState(stages)
  const [stop,setStop] = React.useState(false)
  // console.log(time)
  React.useEffect(() => {
    navigation.setOptions({
      gestureEnabled: false,
      headerLeft: (props) => <Button
        onPress={() => {
          if(progress < 1)
            Alert.alert(
              'Exit is not recommended 🔒',
              'Focus progress has reached '+(progress*100).toFixed(2)+'%. Exiting will empty progress and this tree',
              [
                { text: "Don't leave", style: 'cancel', onPress: () => {} },
                {
                  text: 'Insist on leaving',
                  style: 'destructive',
                  onPress: () => {navigation.pop()}
                },
              ]
            );
          else{
            navigation.pop()
          }
          //设置专注过程不能退出
        }}
        icon={<FontAwesome5Icon name={'chevron-left'} size={21} color='lightblue'/>}
        type='clear'
        containerStyle={{ margin: 10 }}/>
    })
    let subs = true;
    if (progress < 1 && !stop) {
      setTimeout(() => {
        if(subs && progress<1)
          setProgress(progress + 1/(time*60));
        setStage((progress/0.33).toFixed(0))
        // console.log(stage)
        // console.log(grow[stage])
      }, 1000);
    }
    return () => {
      subs = false;
    };
  });

  return (
      <View
        style={{
          margin: 10,
          backgroundColor:stop?'lightgray':'white'
        }}
      >
        <TimingView duration={time} thing={thing} tree={tree} stop = {stop} />

        <View style={{
          top: 51
        }}>
          <Text style={[styles.title,{textAlign: 'center'}]}>🎯 Focusing on: <Text style={{fontSize:30}}>{thing}</Text></Text>
          <Text style={{ fontSize:16 ,fontWeight:'600',textAlign: 'center',marginVertical: 11}}>Rate Of Progress:{(progress*100).toFixed(2)+'%'}</Text>
          <LinearProgress
            style={{height:6,width:"86%",marginLeft:27}}
            value={progress}
            variant="determinate"
          />
          <Button
            disabled={progress == 0}
            onPress={() => {
              setStop(!stop)
            }}
            title={stop?'Start Progress':'Stop Progress'}
            type= {stop?'solid':'outline'}
            containerStyle={{ margin: 23,alignItems: 'center'}}
            buttonStyle={{}}
          />
            {/* 树的成长过程 */}
          <View style={{alignItems: 'center',marginTop:30}}>
            <Image
              style = {[styles.image,{height:180,width:180}]}
              source = {grow[stage].url}
            />
            <Text style={{ fontSize:18 ,fontWeight:'600',marginTop: 8,textAlign: 'center'}}>🌱 Tree {tree} growth is in the {stage} stage</Text>
            <LinearProgress style={{ marginVertical: 10 ,width:"80%"}} color="green" value={stop? 0:undefined} />
            {stop && <Text style={{ fontSize:20 ,fontWeight:'600',marginTop: 23,textAlign: 'center'}}>You have suspended the process, but time is still passing ⏳</Text>}
          </View>
        </View>
      </View>)
};

function HomeScreen({ navigation }) {
  var trees = [{id:1,url: require('./images/1.png')},{id:2,url: require('./images/2.png')},{id:3,url: require('./images/3.png')},
  {id:4,url: require('./images/4.png')},{id:5,url: require('./images/5.png')},{id:6,url: require('./images/6.png')}]
  React.useEffect(() => {   
    const unsubscribe = navigation.addListener('focus', () => {
      fetch("http://192.168.1.106:3000/trees")
      .then((response) => response.json())
      .then((responseData) => {
          console.log(responseData)
          var temp = []
          trees.forEach((element,index)=>{
            if(responseData['trees'][index].if_had){
              temp.push(element)
            } 
          })
          setImages(temp)
          // set(responseData)
      })
      .catch((error) => {
      console.error(error)}) 
    });
    return unsubscribe
  },[navigation])

  // const [data,setData] = useState({});
  // const [detail,setDetail] = useState({});
  const [images,setImages] = useState(trees);
  const [cloop,setCloop] = useState(null); //轮播图ref参数
  const [play,setPlay] = useState(true);
  const [selectedId, setSelectedId] = useState(null);
  const [setStatus, settStatus] = useState(false);
  const [modal, setModal] = useState(false);
  const [editStatus,setEditStatus] = useState(false);
  const [thing, setThing] = useState('');
  const [input, setInput] = useState('');
  const [duration, setDuration] = useState(25);
  const [progress, setProgress] = React.useState(undefined);
  // console.log(Images)
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Badge
        badgeStyle={{height:27}}
        containerStyle={{bottom:100}}
        status= {setStatus? "success":"warning"}
        textStyle={{ color: "#EFE",fontSize: 16}}
        onPress={()=>{if(setStatus) cloop.animateToPage(selectedId-1)}}
        value= {setStatus? "👇You have selected the tree "+images[selectedId-1].id : "Plant a tree from now on 🌱"}
      />
      <Modal
          animationType="fade"
          transparent={true}
          visible={modal}
       >
        <TouchableOpacity
            style={{flex:1,justifyContent:'center', alignItems:'center',backgroundColor:'rgba(0,0,0,0.3)',}}
            onPress={()=>{
                setModal(false)
            }}
        >
          <View style={[styles.flex,{height: editStatus ? 351:321}]}>
              <Ionicons name={'timer'} size={30} color={'green'}  style = {{marginBottom:0}}/>
              <Text style={styles.title}>Tree planting setting</Text>
              { editStatus ?
                <View>
                <Input
                  containerStyle={{}}
                  inputContainerStyle={{width:300}}
                  label="Thing"
                  leftIcon={<FontAwesome5Icon name={'calendar-times'} size={19} />}
                  rightIcon={<TouchableOpacity onPress={()=>{setThing('')}}>
                  <Ionicons name="close" size={20} /></TouchableOpacity>}
                  onChangeText={setThing}
                  value={thing}
                  placeholder="To Do"
                />
                {/* <Text>you will do:{thing}</Text> */}
                {/* <Text style={{ paddingTop:0 }}>Value: {duration}</Text> */}
                <Input
                  containerStyle={{marginBottom:0}}
                  inputContainerStyle={{width:300}}
                  label="Time"
                  leftIcon={<Ionicons name="time" size={21} />}
                  rightIcon={<TouchableOpacity onPress={()=>{setDuration(0),setInput('')}}> 
                  <Ionicons name="close" size={20} /></TouchableOpacity>}
                  onChangeText={value => {setDuration(Number(value),setInput(value))}}
                  value={input} //为了适应滑动条和删除键
                  placeholder="Need Time"
                />
                <Slider
                  value={duration}
                  onValueChange={value => {setDuration(value),setInput(String(value))}}
                  maximumValue={90}
                  minimumValue={0}
                  minimumTrackTintColor='skyblue'
                  step={1}
                  allowTouchTrack
                  containerStyle={{ marginBottom:0,backgroundColor: 'green' }}
                  trackStyle={{ height:7,bottom: 13,  borderRadius: 27 }}
                  thumbStyle={{ height: 20, width: 20, backgroundColor: 'transparent' }}
                  thumbProps={{
                    children: (
                      <FontAwesome5Icon name={'seedling'} size={18} color={'green'} style={{bottom:20}}/>
                    ),
                  }}
                />
                </View> :
                <View>
                  <Card containerStyle={{width:316,backgroundColor:'lightblue'}} wrapperStyle={{}}>
                    <Text style={{fontSize:18}}>Thing: <Text style={{fontSize:16}}>{thing}</Text></Text>
                    <Card.Divider style={{margin:11}} color="#41ae3c"/>
                    <Text style={{fontSize:18}}>Time: <Text style={{fontSize:16}}>{duration}</Text></Text>
                    <Card.Divider  style={{margin:8}}  color="#41ae3c"/>
                    <Text style={{fontSize:18,top:1}}>Tree Species: {selectedId} </Text>
                    <Card.Divider  style={{margin:10,marginBottom:5}}  color="#41ae3c"/>
                    {/* <Text>location: {detail.location}</Text> */}
                  </Card>
                </View>
              } 
              {/* 按钮区域 */}
              <View style={{marginTop:21, flexDirection: "row"}}>
                <Button
                  onPress={()=>
                  {
                    if(editStatus) setEditStatus(false);        //这里设置start，页面跳转
                    else {setModal(false),navigation.navigate('Focus',{time:duration,thing:thing,tree:images[selectedId-1].id})}; 
                  }}
                  // buttonStyle={{ width: 50 }}
                  title={editStatus?"Setup complete":"Start"}
                />{!editStatus && <Button onPress={()=>{setEditStatus(!editStatus)}} containerStyle={{ marginLeft:31 }} title="Edit"/>}
              </View>
          </View>
        </TouchableOpacity>
      </Modal>
      <Carousel
        ref={ref => {setCloop(ref)}}
        delay={2020}   //自动切换的延迟 （毫秒）
        style={{width:318,height:300,bottom:60}}  //轮播组件的样式
        autoplay={play}    //自动轮播
        pageInfo    //在底部显示当前页面下标 / 页面个数
        swiper      //允许手势滑动
        arrows      //允许点击滑动
        leftArrowText={<FontAwesome5Icon name={'chevron-left'} size={21} color='lightblue'/>}
        rightArrowText={<FontAwesome5Icon name={'chevron-right'} size={21} color='lightblue' />}
        pageInfoBackgroundColor={'#fff'}  //分页标示的背景色
        // onAnimateNextPage={(p) => console.log(p)}  //切换页面时的回调
        pageInfoTextStyle={{color:'green'}}     //下面字体样式
        pageInfoTextSeparator={'/'}          //中间的分隔符
      >
      {images.map( (child,index) => {
          return(
            <View style={[{backgroundColor: selectedId == index+1? 'lightblue':'lightgreen' },styles.container]} key={index}>
              <Button
                title= {selectedId == index+1? "Deselect":"Plant this tree "+child.id}
                type="clear"
                icon={<FontAwesome5Icon name={'tree'} size={17}/>}
                containerStyle={{ bottom:31 }}
                onPress={() => {
                  if(!setStatus){settStatus(true);setPlay(false);setSelectedId(index+1);setProgress(0)}
                  else if(selectedId == index+1){
                    settStatus(false);setPlay(true);setSelectedId(null);setProgress(undefined)
                  }
                  else{
                    setSelectedId(index+1)
                  }
                }}/>
              <Image
                  style = {[styles.image,{height:180,width:160,bottom:21}]}
                  source = {child.url}
              />
            </View>
          )
      })}
      </Carousel>
      <LinearProgress
        style={{ width: "86%",height:5,borderRadius:11 }} 
        color="skyblue"
        value={progress}
      />
      <Divider
        style={{ width: "86%" }}
        color="#2089dc"
        subHeader="Start focusing"
        subHeaderStyle={{margin:17}}
        width={3}
      />
      <Button
        title=" Setting"
        icon={<Ionicons name="settings-outline" size={18} />}
        disabled={!setStatus}
        onPress={() => setModal(true)}
      />
    </View>
  );
}

function SettingsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to Details... again"
        onPress={() => navigation.navigate('Settings')}
      />
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
      <Button title="Go back" onPress={() => navigation.goBack()} />
      {/* <Button
        title="Go back to first screen in stack"
        onPress={() => navigation.popToTop()}
      /> */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 11,
  },
  flex: { //弹出框
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
    width:360,
  },
  title: {
    fontSize: 18,
    fontWeight:'800'
  }
});